package org.cgs.web.server.management;

import java.io.IOException;
import java.sql.*;

import javax.servlet.http.*;

import org.apache.log4j.Logger;
import org.cgs.web.database.DatabaseConnector;

public final class ChangePassword extends HttpServlet
{
	private static final long serialVersionUID = 1L;
	private static final Logger LOGGER = Logger.getLogger(ChangePassword.class);

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		// Get student info from web page form
		String courseCode = (String) request.getSession().getAttribute("courseCode");
		String username = request.getParameter("username") == null ? "" : request.getParameter("username");
		String oldPassword = request.getParameter("old") == null ? "" : request.getParameter("old");
		String newPassword = request.getParameter("new") == null ? "" : request.getParameter("new");
		String newPasswordCopy = request.getParameter("new2") == null ? "" : request.getParameter("new2");
		String reason = "";

		// Get ready to make DB call
		boolean errorOccurred = false;
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rSet = null;
		try
		{
			// Get instructor account from DB matching input
			con = DatabaseConnector.getInstance().getConnection();
			pstmt = con.prepareStatement("SELECT * FROM instructorAuthorization WHERE courseCode=? AND netID=?", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
			pstmt.setString(1, courseCode);
			pstmt.setString(2, username);
			rSet = pstmt.executeQuery();

			// Iterate over the results
			if (rSet.next())
			{
				// Get the password stored in the database
				String dbPassword = rSet.getString("password");

				// Check that new password is not empty
				if (newPassword.length() <= 0)
				{
					// New password is empty
					errorOccurred = true;
					reason = "New password is empty";
					return;
				}

				// Check if old password is a match to password stored in DB
				if (!dbPassword.equals(oldPassword))
				{
					// Old password doesn't match
					errorOccurred = true;
					reason = "Old password doesn't match";
					return;
				}

				// Check if new passwords match
				if (!newPassword.equals(newPasswordCopy))
				{
					// New password's don't match
					errorOccurred = true;
					reason = "New password's don't match";
					return;
				}

				// Check to make sure new password is different from old
				// password
				if (newPassword.equals(oldPassword))
				{
					// Old password is same as new password.
					errorOccurred = true;
					reason = "Old password is same as new password";
					return;
				}

				// If we get here, new password is OK so update password to it
				rSet.updateString("password", newPassword);
				rSet.updateRow();

				// Inform user password was changed successfully
				LOGGER.info("Password change was successul");
			} // End if
			else
			{
				// User account does not exist
				errorOccurred = true;
				reason = "User account does not exist";
			} // End else
		} // End try block
		catch (Exception e)
		{
			errorOccurred = true;
			LOGGER.error("Exception thrown while atttempting to change password", e);
		}
		finally
		{
			try
			{
				// Close the ResultSet
				if (rSet != null)
				{
					rSet.close();
				}
			}
			catch (Exception e)
			{
				errorOccurred = true;
				LOGGER.error("Exception cleaning up result set", e);
			}

			try
			{
				// Close the PreparedStatement
				if (pstmt != null)
				{
					pstmt.close();
				}
			}
			catch (Exception e)
			{
				errorOccurred = true;
				LOGGER.error("Exception cleaning up prepared statement", e);
			}

			try
			{
				// Close the connection
				if (con != null)
				{
					con.close();
				}
			}
			catch (Exception e)
			{
				errorOccurred = true;
				LOGGER.error("Exception cleaning up connection to the database", e);
			}
		} // End finally

		// Dispatch to the proper page
		if (errorOccurred)
		{
			LOGGER.info("An error occurred changing the password of instructor " + username + "." + '\n' + "Reason is: " + reason);
			response.sendRedirect("instructor/settings/passwordChangeSuccess.jsp?reason=" + reason);
		}
		else
		{
			response.sendRedirect("instructor/settings/passwordChangeSuccess.jsp");
		}
	} // End method
} // End class
